//公共js,以及基本方法封装 nvue里使用

const fetch = {
  toast: function (tips) {
    uni.showToast({
      title: tips || "网络错误",
      icon: "none",
      duration: 2000,
    });
  },
  request: function ({
    url,
    params = {},
    method = "GET",
    showLoading,
    isJson = false,
  }) {
    //接口请求
    if (showLoading) {
      uni.showLoading({
        mask: true,
        title: "请稍候...",
      });
    }
    return new Promise((resolve, reject) => {
      uni.request({
        url: url,
        data: params,
        method: method, //'GET','POST'
        header: {
          "Content-type": isJson
            ? "application/json;charset=utf-8"
            : "application/x-www-form-urlencoded",
          Authorization: uni.getStorageSync("token") || null,
        },
        success: (res) => {
          showLoading && uni.hideLoading();

          resolve(res.data);
        },
        fail: (res) => {
          fetch.toast("网络错误，请稍后重试！");
          reject(res);
        },
        complete: (res) => {
          switch (res.statusCode) {
            case 200:
              break;
            case 400:
              fetch.toast("错误请求");
              break;
            case 401:
              uni.setStorageSync("token", "");
              uni.reLaunch({
                url: "/pages/login/login",
              });
              fetch.toast("会话已过期，请重新登录");
              break;
            case 403:
              fetch.toast("拒绝访问");
              break;
            case 404:
              fetch.toast("请求错误,未找到该资源");
              break;
            case 405:
              fetch.toast("请求方法未允许");
              break;
            case 408:
              fetch.toast("请求超时");
              break;
            case 500:
              fetch.toast("服务器端出错");
              break;
            case 501:
              fetch.toast("网络未实现");
              break;
            case 502:
              fetch.toast("网络错误");
              break;
            case 503:
              fetch.toast("服务不可用");
              break;
            case 504:
              fetch.toast("网络超时");
              break;
            case 505:
              fetch.toast("http版本不支持该请求");
              break;
            default:
              fetch.toast(`连接错误${res.statusCode}`);
          }
        },
      });
    });
  },
};

module.exports = {
  request: fetch.request,
  toast: fetch.toast,
};
